<template>
  <div class="abnormal-order-upload">
    <h2>异常订单上传</h2>

    <!-- 上传表单区域 -->
    <div class="upload-form-container" style="margin: 0 150px; padding: 20px; border: 1px solid #e6e6e6; border-radius: 8px; background: #f9f9f9;">
      <el-form :model="abnormalOrderForm" :rules="abnormalOrderRules" ref="abnormalOrderFormRef" label-width="120px">
        <!-- 订单号（自动填充） -->
        <el-form-item label="订单号" prop="orderNo">
          <el-input
              v-model="abnormalOrderForm.orderNo"
              placeholder="请输入异常订单的订单号"
              clearable

          />
        </el-form-item>

        <!-- 订单日期（自动填充） -->
        <el-form-item label="订单日期" prop="orderDate">
          <el-date-picker
              v-model="abnormalOrderForm.orderDate"
              type="date"
              placeholder="选择订单创建日期"
              style="width: 100%;"
          />
        </el-form-item>

        <!-- 异常类型 -->
        <el-form-item label="异常类型" prop="abnormalType">
          <el-select
              v-model="abnormalOrderForm.abnormalType"
              placeholder="请选择异常类型"
              style="width: 100%;"
          >
            <el-option label="商品做错" value="商品做错" />
            <el-option label="规格错误（甜度/冰量）" value="规格错误" />
            <el-option label="小料遗漏/错误" value="小料错误" />
            <el-option label="订单漏做" value="订单漏做" />
            <el-option label="支付异常" value="支付异常" />
            <el-option label="其他异常" value="其他异常" />
          </el-select>
        </el-form-item>

        <!-- 异常描述 -->
        <el-form-item label="异常描述" prop="abnormalDesc">
          <el-input
              v-model="abnormalOrderForm.abnormalDesc"
              type="textarea"
              :rows="5"
              placeholder="请详细描述异常情况（如：用户点的少糖去冰，实际做的全糖少冰...）"
          />
        </el-form-item>

        <!-- 处理建议（可选） -->
        <el-form-item label="处理建议（可选）">
          <el-input
              v-model="abnormalOrderForm.suggestion"
              type="textarea"
              :rows="3"
              placeholder="请输入建议的处理方式（如：重新制作）"

          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item style="text-align: center; margin-top: 20px;">
          <el-button type="primary" size="medium" @click="submitAbnormalOrder">提交异常订单</el-button>
          <el-button size="medium" @click="resetForm" style="margin-left: 10px;">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 历史上传记录 -->
    <div class="history-record" style="margin: 30px 20px 20px;">
      <h3 style="border-bottom: 1px solid #e6e6e6; padding-bottom: 10px;">历史上传记录</h3>
      <el-table
          :data="historyList"
          border
          stripe
          style="width: 100%; margin-top: 10px;"
          :empty-text="historyListLoading ? '加载中...' : '暂无历史上传记录'"
      >
        <el-table-column label="记录ID" prop="id" width="100" align="center" />
        <el-table-column label="订单号" prop="orderNo" width="100" align="center"/>
        <el-table-column label="异常类型" prop="abnormalType" width="210" align="center" />
        <!-- 提交时间（使用格式化方法处理时间戳） -->
        <el-table-column label="提交时间" width="280" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="处理状态" prop="handleStatus" width="203" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.handleStatus === '待处理' ? 'warning' : scope.row.handleStatus === '处理中' ? 'info' : 'success'">
              {{ scope.row.handleStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190" align="center">
          <template #default="scope">
            <el-button type="text" @click="viewDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 15px; text-align: right;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[10, 20, 30]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        />
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog title="异常订单详情" v-model="isDetailDialogOpen" width="600px">
      <div class="detail-content">
        <div class="detail-item">
          <span class="detail-label">记录ID：</span>
          <span class="detail-value">{{ currentDetail.id || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">订单号：</span>
          <span class="detail-value">{{ currentDetail.orderNo || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">订单日期：</span>
          <span class="detail-value">{{ formatDate(currentDetail.orderDate) || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">异常类型：</span>
          <span class="detail-value">{{ currentDetail.abnormalType || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">异常描述：</span>
          <span class="detail-value">{{ currentDetail.abnormalDesc || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">处理建议：</span>
          <span class="detail-value">{{ currentDetail.suggestion || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">提交人：</span>
          <span class="detail-value">{{ currentDetail.createBy || '员工' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">提交时间：</span>
          <span class="detail-value">{{ formatDate(currentDetail.createTime) || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">处理状态：</span>
          <span class="detail-value">
            <el-tag :type="currentDetail.handleStatus === '待处理' ? 'warning' : currentDetail.handleStatus === '处理中' ? 'info' : 'success'">
              {{ currentDetail.handleStatus || '-' }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item" v-if="currentDetail.handleRemark">
          <span class="detail-label">处理备注：</span>
          <span class="detail-value">{{ currentDetail.handleRemark }}</span>
        </div>
        <div class="detail-item" v-if="currentDetail.handleTime">
          <span class="detail-label">处理时间：</span>
          <span class="detail-value">{{ formatDate(currentDetail.handleTime) }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="isDetailDialogOpen = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import http from '@/axios/http'

// 获取路由实例，用于接收参数
const route = useRoute()

// 表单数据
const abnormalOrderFormRef = ref(null)
const abnormalOrderForm = ref({
  orderNo: '', // 订单号（自动填充）
  orderDate: '', // 订单日期（自动填充）
  abnormalType: '',
  abnormalDesc: '',
  suggestion: '',
  createBy: '员工'
})

// 表单校验规则
const abnormalOrderRules = ref({
  orderNo: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  orderDate: [{ required: true, message: '请选择订单日期', trigger: 'change' }],
  abnormalType: [{ required: true, message: '请选择异常类型', trigger: 'change' }],
  abnormalDesc: [{ required: true, message: '请描述异常情况', trigger: 'blur' }, { min: 5, message: '描述至少5个字符', trigger: 'blur' }]
})

// 历史记录相关
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const historyList = ref([])
const historyListLoading = ref(false)

// 详情弹窗
const isDetailDialogOpen = ref(false)
const currentDetail = ref({})

// 监听路由参数，自动填充表单
watch(
    () => route.query,
    (newQuery) => {
      if (newQuery.orderNo) {
        abnormalOrderForm.value.orderNo = String(newQuery.orderNo)
      }
      if (newQuery.orderDate) {
        const date = new Date(newQuery.orderDate)
        if (!isNaN(date.getTime())) {
          abnormalOrderForm.value.orderDate = date
        } else {
          ElMessage.warning('订单日期格式错误，请手动选择')
        }
      }
    },
    { immediate: true }
)

// 页面加载时获取历史记录
onMounted(() => {
  getHistoryList()
})

// 提交异常订单
const submitAbnormalOrder = async () => {
  try {
    await abnormalOrderFormRef.value.validate()

    const submitForm = {
      ...abnormalOrderForm.value,
      orderDate: abnormalOrderForm.value.orderDate
          ? new Date(abnormalOrderForm.value.orderDate).toISOString()
          : '',
      handleStatus: '待处理'
    }

    const res = await http.post('/glsb/upload_abnormal_order', submitForm)
    if (res.data.result === 'success') {
      ElMessage.success('异常订单上传成功！')
      resetForm()
      getHistoryList()
    } else {
      ElMessage.error('上传失败：' + (res.data.msg || '未知错误'))
    }
  } catch (err) {
    ElMessage.error('表单校验失败，请检查必填项')
    console.error(err)
  }
}

// 重置表单
const resetForm = () => {
  abnormalOrderForm.value = {
    orderNo: '',
    orderDate: '',
    abnormalType: '',
    abnormalDesc: '',
    suggestion: '',
    createBy: '员工'
  }
  if (abnormalOrderFormRef.value) {
    abnormalOrderFormRef.value.resetFields()
  }
}

// 获取历史记录
const getHistoryList = async () => {
  try {
    historyListLoading.value = true
    const res = await http.post('/glsb/get_abnormal_order_list', {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      createBy: '员工'
    })
    if (res.data.result === 'success') {
      historyList.value = res.data.data.list || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error('获取历史记录失败：' + res.data.msg)
    }
  } catch (err) {
    ElMessage.error('网络错误，请重试')
    console.error(err)
  } finally {
    historyListLoading.value = false
  }
}

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  getHistoryList()
}
const handleCurrentChange = (val) => {
  pageNum.value = val
  getHistoryList()
}

// 查看详情
const viewDetail = (row) => {
  currentDetail.value = { ...row }
  isDetailDialogOpen.value = true
}

// 核心：时间戳格式化方法（兼容数字时间戳和字符串）
const formatDate = (value) => {
  if (!value) return '';

  // 处理时间戳（数字类型，如1761031470000）
  const timestamp = typeof value === 'number'
      ? value
      : new Date(value).getTime(); // 处理字符串类型日期

  if (isNaN(timestamp)) return '无效时间';

  const date = new Date(timestamp);
  // 格式化为：YYYY-MM-DD HH:MM:SS（24小时制）
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false // 禁用12小时制
  });
};
</script>

<style scoped>
.abnormal-order-upload {
  padding: 20px;
  background: #fff;
  min-height: 100vh;
}
.upload-form-container {
  max-width: 800px;
  margin: 0 auto;
}
.history-record {
  max-width: 1200px;
  margin: 30px auto 20px;
}
.detail-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 10px 0;
}
.detail-item {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}
.detail-label {
  font-weight: 500;
  width: 100px;
  flex-shrink: 0;
  color: #666;
}
.detail-value {
  flex: 1;
  color: #333;
  line-height: 1.5;
}
</style>